<template>
  <!-- 来电查询 -->
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item class="merge-item">
        <el-select v-model="qtype" style="width: 170px; margin-right: 2px;">
          <el-option value="phone" label="来电号码" />
          <el-option value="csmCode" label="客户编号" />
          <el-option value="csmName" label="客户名称" />
        </el-select>
        <el-input v-model.trim="txt" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="接听人:">
        <el-select v-model="query.answerId" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in transactorList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="通话任务类型:" prop="taskType">
        <el-select v-model="query.taskType" clearable placeholder="请选择">
          <el-option
            v-for="item in taskTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :table-form-merge="2" class="merge-item" label="来电时间:">
        <el-date-picker
          v-model="date"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
          :clearable="false"
          :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>
      <el-form-item label="接听状态:" prop="callStatus">
        <el-select v-model="query.callStatus" clearable placeholder="请选择">
          <el-option
            v-for="item in callStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button
          v-permission="1"
          type="primary"
          icon="el-icon-search"
          @click="search"
        >查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;">
      <div>
        <el-button
          type="primary"
          icon="el-icon-download"
          @click="exportFile"
        >导出</el-button>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      :row-class-name="tableRowClassName"
      @fetch="fetchData"
    />
    <audio id="callRecordAudio">浏览器不支持</audio>
  </div>
</template>

<script>
  import { queryCallUpList, queryCallUpListExport, queryMap } from '@/api'
  import { parseTime } from '@/utils'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { formatColumnMap } from '@/utils'
  import moment from 'dayjs'
  import { mapGetters } from 'vuex'

  export default {
    name: 'callUp',
    props: {
      transactorList: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        callRecordAudio: undefined,
        actionColWidth: 80,
        callStatusMap: [],
        taskTypeMap: [],
        qtype: 'phone',
        txt: '',
        date: [moment().startOf('day'), moment().endOf('day')],
        query: {
          answerId: '',
          taskType: '',
          callStatus: ''
        },
        searchParams: {},
        tableData: {
          total: 0,
          data: []
        }
      }
    },
    computed: {
      ...mapGetters(['exportDomain', 'corpSettingData']),
      column: function() {
        return [
          {
            type: 'index'
          },
          {
            prop: 'callCode',
            label: '来电编号',
            width: 160
          },
          {
            prop: 'phone',
            label: '来电号码',
            width: 130,
            render: (h, { row }) => {
              if (row.phone) {
                return (
                <span>
                  <svg-icon icon-class='call' onClick={e => window.pbx.dial(row.phone, e)} />{row.phone}
                </span>
              )
              }
              return ''
            }
          },
          {
            prop: 'csmCode',
            label: '客户编号'
          },
          {
            prop: 'csmName',
            label: '客户名称'
          },
          {
            prop: 'csmAddress',
            label: '客户地址',
            width: 180
          },
          {
            prop: 'taskType',
            label: '通话任务类型',
            width: 130,
            render: (h, { row }) => (
            <span>
              {formatColumnMap(this.taskTypeMap, 'value', row.taskType, 'desc') || '其他'}
            </span>
          )
          },
          {
            prop: 'taskCode',
            label: '通话任务单号',
            width: 130
          },
          {
            prop: 'num',
            label: '坐席号'
          },
          {
            prop: 'answer',
            label: '接听人'
          },
          {
            prop: 'callStatus',
            label: '接听状态',
            render: (h, { row }) => (
            <span>
              {(row.callStatus &&
                formatColumnMap(this.callStatusMap, 'value', row.callStatus, 'desc')) ||
                '已接听'}
            </span>
          )
          },
          {
            prop: 'startDt',
            label: '来电时间',
            width: 160,
            render: (h, { row }) => (
            <span>
              {row.startDt && parseTime(row.startDt, '{y}-{m}-{d} {h}:{i}:{s}')}
            </span>
          )
          },
          {
            prop: 'endDt',
            label: '挂机时间',
            width: 160,
            render: (h, { row }) => (
            <span>{row.endDt && parseTime(row.endDt, '{y}-{m}-{d} {h}:{i}:{s}')}</span>
          )
          },
          {
            prop: 'waitTimeSpan',
            label: '等待时长(秒)',
            align: 'right',
            width: 130
          },
          {
            prop: 'timeSpan',
            align: 'right',
            label: '来电时长(秒)',
            width: 130
          },
          {
            prop: 'serviceStar',
            label: '服务评价',
            render: (h, { row }) => (
            <span>{this.nearStationNameFormat(row.serviceStar)}</span>
          )
          },
          {
            label: '语音',
            prop: 'fileUrl',
            fixed: 'right',
            width: 65,
            render: (h, scope) => {
              return (
              <div>
                {scope.row.fileUrl && scope.row.paused && (
                  <i
                    class='colBtn el-icon-video-play'
                    onClick={() => this.play(scope, scope.row.callId)}
                  ></i>
                )}
                &nbsp;
                {scope.row.fileUrl && !scope.row.paused && (
                  <i
                    class='colBtn el-icon-video-pause'
                    onClick={() => this.play(scope, scope.row.callId)}
                  ></i>
                )}
                &nbsp;
                {scope.row.fileUrl && (
                  <i
                    class='colBtn el-icon-download'
                    onClick={() => this.download(scope.row)}
                  ></i>
                )}
              </div>
              )
            }
          }
        ]
      }
    },
    created() {
      this.queryOptionsMap()
    },
    mounted() {
      this.callRecordAudio = document.getElementById('callRecordAudio')
    },
    methods: {
      nearStationNameFormat(val) {
        switch (val) {
        case 0:
          return ''
        case 2:
          return '一般'
        case 3:
          return '不满意'
        default:
          return '满意'
        }
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          callStatus: this.query.callStatus || 0,
          taskType: this.query.taskType || -1,
          currentPage,
          pageSize
        }
        if (this.date && this.date.length > 0) {
          query.startDt = moment(this.date[0]).format()
          query.startDtEnd = moment(this.date[1]).format()
        }
        if (this.txt) query[this.qtype] = this.txt
        const diff = moment(this.date[1]).diff(moment(this.date[0]), 'days')
        if (diff > 93) {
          this.$message.error('选择来电时间相差不能超过3个月')
          return
        }
        const res = await queryCallUpList(query)
        this.searchParams = query
        this.tableData.data = res.data.rows.map((item) => {
          return {
            ...item,
            paused: true
          }
        })
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res1, res2] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'CallTaskType' }),
          mergeAsyncFunc(queryMap, { enumName: 'CallStatus' })
        ])
        this.taskTypeMap = res1.data // 通话任务类型
        this.callStatusMap = res2.data // 接听状态
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      exportFile() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.column))
          copyColumn.pop()
          const str = {}
          copyColumn.forEach((item) => {
            str[item.prop] = item.label
          })
          const params = this.searchParams
          if (this.date && this.date.length > 0) {
            params.startDt = this.date[0]
            params.startDtEnd = this.date[1]
          }
          queryCallUpListExport({
            paramInfo: _this._getQuery(params),
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      play(scope, id) {
        if (this.callRecordAudio.dataset.id === id) {
          if (this.callRecordAudio.paused) {
            this.callRecordAudio.play()
            scope.row.paused = false
            this.callRecordAudio.addEventListener(
              'ended',
              function() {
                scope.row.paused = true
              },
              false
            )
          } else {
            this.callRecordAudio.pause()
          }
        } else {
          this.callRecordAudio.dataset.id = id
          this.callRecordAudio.pause()
          this.callRecordAudio.src = `http://${this.corpSettingData.pbxURL}/download/audio?path=${scope.row.fileUrl}`
          this.callRecordAudio.play()
          scope.row.paused = false
          this.callRecordAudio.addEventListener(
            'ended',
            function() {
              scope.row.paused = true
            },
            false
          )
        }
      },
      download(row) {
        const path = `http://${this.corpSettingData.pbxURL}/download/audio?path=${row.fileUrl}`
        window.open(path)
      },
      // 设置颜色
      tableRowClassName({ row }) {
        if (row.callStatus === 2) {
          return 'success-row'
        } else if (row.callStatus === 3) {
          return 'warning-row'
        }
        return ''
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach((it) => {
                width += it.offsetWidth + 10
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.app-page {
  /deep/ .colBtn.el-icon-video-play,
  /deep/ .colBtn.el-icon-video-pause,
  /deep/ .colBtn.el-icon-download {
    font-size: 20px;
    color: #01999f;
    cursor: pointer;
  }
}
/deep/ .el-table tr.warning-row {
  background: #ffdfdf;
}
.el-table .success-row {
  background-color: #f0f9eb;
}
</style>
